import requests
import re
import time

# requests.session,创建一个保持登录凭据的session实例
login_session = requests.session()
# 1、get请求，获取token信息
token_url = "http://account.chinaunix.net/login"
header = {
    "Host": "account.chinaunix.net",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/86.0.4240.75 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,"
              "application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

# 发送第一个get请求
token_response = login_session.get(url=token_url, headers=header)
# 通过正则表达式获取token值
token_search = re.compile(r"XSRF-TOKEN=(.*?);")
token_value = token_search.search(token_response.headers.get("Set-Cookie"))

# 2、post请求
login_url = "http://account.chinaunix.net/login/login"
data = {
    "username": "dazhuang_imooc",
    "password": "abcd1234",
    "_token": token_value,
    "_t": int(time.time())
}

# 发送Post请求，提交用户名密码,注意不要忘记携带data
login_response = login_session.post(url=login_url, headers=header, data=data)
print(login_response.text)

index_url = "http://account.chinaunix.net/ucenter/user/index"
# 一定要使用login_session
index_response = login_session.get(url=index_url, headers=header)
print(index_response.text)